package com.xuecheng.framework.util;


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 此文件作为视频处理的父类，提供：
 * 1、查看视频时长
 * 2、校验两个视频时长是否相等
 *
 */
public class VideoUtil {

    String ffmpegPath = "D:\\Program Files\\ffmpeg-20180227-fa0c9d6-win64-static\\bin\\ffmpeg.exe";//ffmpeg的安装位置

    public VideoUtil(String ffmpegPath) {
        this.ffmpegPath = ffmpegPath;
    }

    //检查视频时间是否一致
    public boolean checkVideoTime(String source, String target) {
        String sourceTime = getVideoTIme(source);
        //取出时分秒
        sourceTime = sourceTime.substring(0,sourceTime.lastIndexOf("."));
        String targetTime = getVideoTIme(target);
        //取出时分秒
        targetTime = targetTime.substring(0,targetTime.lastIndexOf("."));
        if(sourceTime == null || targetTime == null){
            return false;
        }
        if(sourceTime.equals(targetTime)){
            return true;
        }
        return false;
    }

    //获取视频时间(时：分：秒：毫秒)
    public String getVideoTIme(String videoPath) {
        /*
        ffmpeg -i  lucene.mp4
         */
        List<String> commend = new ArrayList<>();
        commend.add("ffmpeg");
        commend.add("-i");
        commend.add(videoPath);
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command(commend);
            //将标准输入流与错误输入流合并，通过标准输入流获取信息
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            String outputString = waitFor(process);
            int start = outputString.trim().indexOf("Duration: ");
            if(start>=0){
                int end = outputString.trim().indexOf(", start:");
                if(end>=0){
                    String time = outputString.substring(start+10,end);
                    if(time!=null && !time.equals("")){
                        return time.trim();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String waitFor(Process process) {
        InputStream in = null;
        InputStream error = null;
        String result = "error";
        int exitValue = -1;
        StringBuffer outputString = new StringBuffer();
        try {
            in = process.getInputStream();
            error = process.getErrorStream();
            boolean finished = false;
            int maxRetry = 600;//每次休眠1秒，最长执行时间10分种
            int retry = 0;
            while (!finished) {
                if (retry > maxRetry) {
                    return "error";
                }
                try {
                    while (in.available() > 0) {
                        Character c = new Character((char) in.read());
                        outputString.append(c);
                    }
                    while (error.available() > 0) {
                        Character c = new Character((char) in.read());
                        outputString.append(c);
                    }
                    //进程未结束时调用exitValue将抛出异常
                    exitValue = process.exitValue();
                    finished = true;

                } catch (IllegalThreadStateException e) {
                    Thread.currentThread().sleep(1000);//休眠1秒
                    retry++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
        return outputString.toString();
    }

}
